"""
文件处理工具模块
包含文件清理、验证等实用功能
"""
import os
import glob
import time
import json
import zipfile
from io import BytesIO


def cleanup_temp_files(temp_dir='/data/temp/images', max_age_minutes=25):
    """清理指定目录下超过指定时间的jpg文件"""
    try:
        if not os.path.exists(temp_dir):
            return
            
        current_time = time.time()
        max_age_seconds = max_age_minutes * 60
        
        for jpg_file in glob.glob(os.path.join(temp_dir, '*.jpg')):
            try:
                file_mtime = os.path.getmtime(jpg_file)
                if current_time - file_mtime > max_age_seconds:
                    os.remove(jpg_file)
                    print(f"已删除过期临时文件: {jpg_file}")
            except OSError as e:
                print(f"删除临时文件失败: {jpg_file}, 错误: {e}")
                
    except Exception as e:
        print(f"清理临时文件时出错: {e}")


def validate_json_file(file_stream, max_size=10*1024*1024):
    """验证JSON文件格式和大小"""
    # 检查文件大小
    file_stream.seek(0, os.SEEK_END)
    file_size = file_stream.tell()
    file_stream.seek(0)
    
    if file_size > max_size:
        return False, f'JSON文件过大，请确保文件小于{max_size//1024//1024}MB。'
    
    try:
        # 验证JSON格式
        content = file_stream.read()
        json.loads(content.decode('utf-8'))
        file_stream.seek(0)  # 重置文件指针
        return True, None
    except json.JSONDecodeError:
        return False, '无效的JSON文件格式。'
    except Exception as e:
        return False, f'验证文件时出错: {e}'


def validate_zip_file(file_stream, max_size=100*1024*1024):
    """验证ZIP文件格式和大小"""
    # 检查文件大小
    file_stream.seek(0, os.SEEK_END)
    file_size = file_stream.tell()
    file_stream.seek(0)
    
    if file_size > max_size:
        return False, f'ZIP文件过大，请确保模型文件小于{max_size//1024//1024}MB。'
    
    try:
        with zipfile.ZipFile(file_stream, 'r') as zip_ref:
            # 安全检查：确保ZIP文件不包含危险路径
            for name in zip_ref.namelist():
                if os.path.isabs(name) or ".." in name:
                    return False, 'ZIP文件包含不安全的路径。'
        
        file_stream.seek(0)  # 重置文件指针
        return True, None
        
    except zipfile.BadZipFile:
        return False, '无效的ZIP文件格式。'
    except Exception as e:
        return False, f'验证ZIP文件时出错: {e}'


def create_model_zip(model_path, labels_path):
    """创建模型ZIP包"""
    try:
        zip_buffer = BytesIO()
        with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
            zip_file.write(model_path, os.path.basename(model_path))
            zip_file.write(labels_path, os.path.basename(labels_path))
        
        zip_buffer.seek(0)
        return zip_buffer.getvalue()
    except Exception as e:
        raise Exception(f"打包模型时出错: {e}")


def extract_model_from_zip(zip_file, model_folder):
    """从ZIP文件中提取模型文件"""
    try:
        with zipfile.ZipFile(zip_file, 'r') as zip_ref:
            # 提取到模型文件夹
            zip_ref.extractall(model_folder)
            
            # 从zip文件中查找模型文件名
            model_filename = None
            labels_filename = None
            for name in zip_ref.namelist():
                if name.startswith('trained_model_') and name.endswith('.pth'):
                    model_filename = name
                elif name.startswith('labels_') and name.endswith('.json'):
                    labels_filename = name
            
            if model_filename and labels_filename:
                return model_filename, None
            else:
                return None, 'ZIP文件中未找到有效的模型文件或标签文件。'
                
    except Exception as e:
        return None, f'处理ZIP文件时出错: {e}'
